<template>
  <div class="article-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-header">
        <el-form :inline="true" class="search-form">
          <el-form-item label="文章名:">
            <el-input placeholder="请输入搜索文章名" v-model="keyword" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :disabled="!keyword"
              @click="search"
              :icon="Search"
            >
              搜索
            </el-button>
            <el-button @click="reset" :icon="Refresh">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="openPublishDialog" :icon="Plus">发布文章</el-button>
      </div>
    </el-card>

    <!-- 文章列表 -->
    <div class="article-list" v-loading="loading">
      <el-empty v-if="articleList.length === 0" description="暂无文章数据"></el-empty>
      <el-row :gutter="20" v-else>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="article in articleList" :key="article.article_id" class="article-col">
          <el-card class="article-card" shadow="hover">
            <div class="article-header">
              <h3 class="article-title">{{ article.article_title }}</h3>
              <el-tag size="small" type="info">{{ article.article_ip_address }}</el-tag>
            </div>
            
            <div class="article-media">
              <el-image
                v-if="article.article_image_url && judge(article.article_image_url)"
                class="article-image"
                :src="article.article_image_url"
                fit="cover"
                lazy
                :preview-src-list="showImg(article.article_image_url)"
              />
              <video 
                v-else-if="article.article_image_url" 
                class="article-video"
                :src="article.article_image_url" 
                controls
                muted
              ></video>
              <div v-else class="no-media">暂无媒体资源</div>
            </div>
            
            <div class="article-content">
              <p class="content-preview">{{ truncateContent(article.article_content) }}</p>
            </div>
            
            <div class="article-footer">
              <div class="article-info">
                <div class="info-item">
                  <el-icon><Calendar /></el-icon>
                  <span>{{ formatTime(article.article_published_at) }}</span>
                </div>
                <div class="info-item">
                  <el-icon><Star /></el-icon>
                  <span>{{ article.article_likes }} 赞</span>
                </div>
              </div>
              
              <div class="article-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  :icon="Edit"
                  @click="editArticle(article)"
                >
                  编辑
                </el-button>
                <el-popconfirm
                  title="确定要删除这篇文章吗？"
                  @confirm="deleteArticle(article)"
                >
                  <template #reference>
                    <el-button type="danger" size="small" :icon="Delete">删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[8, 12, 24, 36]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </div>

    <!-- 发布/编辑文章对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="70%" 
      destroy-on-close
      draggable
    >
      <el-form
        ref="articleFormRef"
        :model="form"
        :rules="rules"
        label-position="right"
        label-width="120px"
        class="article-form"
      >
        <!-- 标题 -->
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" maxlength="50" show-word-limit />
        </el-form-item>
        
        <!-- 内容 -->
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            v-model="form.content"
            placeholder="请输入文章内容"
            rows="6"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
        
        <!-- 图片上传 -->
        <el-form-item label="上传图片">
          <div v-if="!uploadedImageUrl" class="upload-container">
            <el-upload
              class="image-uploader"
              :action="uploadUrl" 
              name="image"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :limit="1"
              list-type="picture-card"
            >
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">点击上传</div>
            </el-upload>
          </div>
          
          <!-- 上传后的图片展示 -->
          <div v-else class="preview-container">
            <el-image :src="uploadedImageUrl" class="preview-image" fit="contain" />
            <el-button type="primary" text @click="resetUpload" class="change-button">
              <el-icon><RefreshRight /></el-icon> 更换图片
            </el-button>
          </div>
        </el-form-item>
        
        <!-- 作者 ID -->
        <el-form-item label="作者 ID" prop="author_id">
          <el-input
            v-model.number="form.author_id"
            type="number"
            placeholder="作者 ID"
            disabled
          />
        </el-form-item>
        
        <!-- IP 地址 -->
        <el-form-item label="发布地址" prop="address">
          <el-select v-model="form.address" placeholder="请选择省份" filterable>
            <el-option
              v-for="province in provinces"
              :key="province.code"
              :label="province.name"
              :value="province.name"
            />
          </el-select>
        </el-form-item>
        
        <!-- 点赞数 -->
        <el-form-item label="点赞数" prop="likes">
          <el-input-number
            v-model="form.likes"
            :min="0"
            :max="10000"
            controls-position="right"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm(articleFormRef)">提交</el-button>
          <el-button @click="resetForm(articleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { addArticle, deleteArticleSync, GetAllArticleSync, updateArticle } from "@/api/article";
import { formatTime } from "@/utils/time.ts";
import { Search, Refresh, Plus, Edit, Delete, Calendar, Star, RefreshRight } from "@element-plus/icons-vue";

// 数据加载状态
const loading = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(8);
const total = ref(0);

// 表单引用
const articleFormRef = ref<FormInstance>();

const uploadUrl = computed(() => process.env.NODE_ENV === 'production' ? 'https://back.xuxiao888.com/upload' : 'http://localhost:5000/upload');
// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: "请输入文章标题", trigger: "blur" },
    { min: 2, max: 50, message: "标题长度应在 2 到 50 个字符之间", trigger: "blur" }
  ],
  content: [
    { required: true, message: "请输入文章内容", trigger: "blur" }
  ],
  address: [
    { required: true, message: "请选择发布地址", trigger: "change" }
  ],
  likes: [
    { required: true, message: "请设置点赞数", trigger: "blur" }
  ]
});

// 初始化数据
onMounted(() => {
  fetchArticles();
});

// 表单数据
const form = ref({
  articleId: undefined as number | undefined,
  title: "",
  content: "",
  imageUrl: "",
  author_id: 4,
  address: "",
  likes: 0,
});

// 对话框标题
const dialogTitle = computed(() => {
  return form.value.articleId ? "编辑文章" : "发布文章";
});

// 搜索关键词
const keyword = ref("");

// 对话框可见性
const dialogVisible = ref(false);

// 上传图片URL
const uploadedImageUrl = ref("");

// 文章列表
const articleList = ref<any[]>([]);

// 省份列表
const provinces = ref([
  { code: "01", name: "北京" },
  { code: "02", name: "天津" },
  { code: "03", name: "上海" },
  { code: "04", name: "重庆" },
  { code: "05", name: "河北" },
  { code: "06", name: "山西" },
  { code: "07", name: "辽宁" },
  { code: "08", name: "吉林" },
  { code: "09", name: "黑龙江" },
  { code: "10", name: "江苏" },
  { code: "11", name: "浙江" },
  { code: "12", name: "安徽" },
  { code: "13", name: "福建" },
  { code: "14", name: "江西" },
  { code: "15", name: "山东" },
  { code: "16", name: "河南" },
  { code: "17", name: "湖北" },
  { code: "18", name: "湖南" },
  { code: "19", name: "广东" },
  { code: "20", name: "广西" },
  { code: "21", name: "海南" },
  { code: "22", name: "四川" },
  { code: "23", name: "贵州" },
  { code: "24", name: "云南" },
  { code: "25", name: "西藏" },
  { code: "26", name: "陕西" },
  { code: "27", name: "甘肃" },
  { code: "28", name: "青海" },
  { code: "29", name: "宁夏" },
  { code: "30", name: "新疆" },
  { code: "31", name: "台湾" },
  { code: "32", name: "香港" },
  { code: "33", name: "澳门" },
]);

// 判断是否为图片
const judge = (url: string) => {
  return typeof url === 'string' && (url.endsWith('.png') || url.endsWith('.jpg') || url.endsWith('.jpeg') || url.endsWith('.gif'));
};

// 获取图片预览列表
const showImg = (url: string) => {
  return [url];
};

// 截断内容预览
const truncateContent = (content: string) => {
  if (!content) return "";
  return content.length > 100 ? content.substring(0, 100) + "..." : content;
};

// 搜索文章
const search = () => {
  if (!keyword.value.trim()) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }
  
  // 根据关键词过滤文章列表
  fetchArticles();
};

// 重置搜索
const reset = () => {
  keyword.value = "";
  fetchArticles();
};

// 打开发布对话框
const openPublishDialog = () => {
  resetForm();
  dialogVisible.value = true;
};

// 获取文章列表
const fetchArticles = async () => {
  loading.value = true;
  try {
    const res = await GetAllArticleSync();
    if (res && res.data) {
      // 如果有搜索关键词，过滤文章列表
      if (keyword.value.trim()) {
        articleList.value = res.data.filter((article: any) => 
          article.article_title.toLowerCase().includes(keyword.value.toLowerCase()) ||
          article.article_content.toLowerCase().includes(keyword.value.toLowerCase())
        );
      } else {
        articleList.value = res.data;
      }
      
      total.value = articleList.value.length;
    } else {
      articleList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取文章列表失败:", error);
    ElMessage.error("获取文章列表失败");
    articleList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 编辑文章
const editArticle = (article: any) => {
  form.value = {
    articleId: article.article_id,
    title: article.article_title,
    content: article.article_content,
    imageUrl: article.article_image_url,
    author_id: 4,
    address: article.article_ip_address,
    likes: article.article_likes,
  };
  
  if (article.article_image_url) {
    uploadedImageUrl.value = article.article_image_url;
  } else {
    uploadedImageUrl.value = "";
  }
  
  dialogVisible.value = true;
};

// 删除文章
const deleteArticle = async (article: any) => {
  loading.value = true;
  try {
    const articleIds = {
      "articleIds": [article.article_id]
    };
    
    const res = await deleteArticleSync(articleIds);
    if (res.status === 1) {
      ElMessage.success("删除成功");
      await fetchArticles();
    } else {
      ElMessage.error("删除失败: " + (res.message || "未知错误"));
    }
  } catch (error) {
    console.error("删除文章失败:", error);
    ElMessage.error("删除文章失败");
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  
  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        if (form.value.articleId) {
          // 更新文章
          const res = await updateArticle(form.value);
          if (res.status === 1) {
            ElMessage.success("编辑成功");
            dialogVisible.value = false;
            await fetchArticles();
          } else {
            ElMessage.error("编辑失败: " + (res.message || "未知错误"));
          }
        } else {
          // 添加文章
          const res = await addArticle(form.value);
          if (res.code === 200) {
            ElMessage.success("添加成功");
            dialogVisible.value = false;
            await fetchArticles();
          } else {
            ElMessage.error("添加失败: " + (res.message || "未知错误"));
          }
        }
      } catch (error) {
        console.error("提交文章失败:", error);
        ElMessage.error("提交文章失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

// 重置表单
const resetForm = (formEl?: FormInstance) => {
  if (formEl) {
    formEl.resetFields();
  }
  
  form.value = {
    articleId: undefined,
    title: "",
    content: "",
    imageUrl: "",
    author_id: 4,
    address: "",
    likes: 0,
  };
  
  uploadedImageUrl.value = "";
};

// 上传成功回调
const handleUploadSuccess = (response: any, file: any) => {
  uploadedImageUrl.value = URL.createObjectURL(file.raw);
  form.value.imageUrl = response.imageUrl;
  ElMessage.success("上传成功");
};

// 上传前验证
const beforeUpload = (file: any) => {
  const isImage = file.type.startsWith("image/");
  const isLt4M = file.size / 1024 / 1024 < 4;
  
  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  
  if (!isLt4M) {
    ElMessage.error("上传图片大小不能超过 4MB！");
    return false;
  }
  
  return true;
};

// 重置上传
const resetUpload = () => {
  uploadedImageUrl.value = "";
  form.value.imageUrl = "";
};

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  // 实际项目中可能需要重新请求数据，这里简化处理
};

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  // 实际项目中可能需要重新请求数据，这里简化处理
};
</script>

<style scoped>
.article-management {
  padding: 20px 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  display: flex;
  align-items: center;
}

.article-list {
  margin-top: 20px;
}

.article-col {
  margin-bottom: 20px;
}

.article-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: all 0.3s;
}

.article-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.article-title {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.article-media {
  height: 160px;
  overflow: hidden;
  margin-bottom: 12px;
  border-radius: 4px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.article-image,
.article-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-media {
  color: #909399;
  font-size: 14px;
}

.article-content {
  flex: 1;
  margin-bottom: 12px;
}

.content-preview {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  margin: 0;
}

.article-footer {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.article-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.article-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.article-form {
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #fff;
}

.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.upload-text {
  color: #8c939d;
  font-size: 12px;
  text-align: center;
  margin-top: 8px;
}

.preview-container {
  position: relative;
  width: 200px;
}

.preview-image {
  width: 100%;
  height: 200px;
  border-radius: 4px;
  object-fit: cover;
}

.change-button {
  margin-top: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
